<template>
  <div class="song_contaner padd100">
    <el-row :gutter="20">
      <el-col :lg="20" style="margin-bottom:20px">
        <div class="song_warpper">
          <div class="left_song_img">
            <img :src="songs.al.picUrl+ '?param=260y260'" alt="">
          </div>
          <div class="right_song_info">
            <div class="song_title">
              <el-tag>单曲</el-tag>
              <h1>{{songs.name}}</h1>
            </div>
            <div class="song_desc">
              <div class="song_desc_item">
                <span>歌手：</span>
                <div v-for="(item,i) in songs.ar" :key="item.id">
                  <span v-if="i !== 0" style="margin:0 4px"> / </span>
                  <el-link type="primary" @click="()=>{router.push({name:'artist-detail',params:{id:item.id}})}">
                    {{item.name}} </el-link>
                </div>
              </div>
              <div class="song_desc_item">
                <span>所属专辑：</span>
                <el-link type="primary" @click="()=>{router.push({name:'album-detail',params:{id:songs.al.id}})}">
                  {{songs.al.name}}</el-link>
              </div>
            </div>
            <div class="r_m_opea">
              <template v-if="songs.fee == 1 || songs.license">
                <el-button type="danger" :icon="VideoPlay" disabled>VIP歌曲暂不支持播放</el-button>
              </template>
              <template v-else>
                <el-button type="primary" :icon="VideoPlay" @click="play" :disabled="musicSuccess?false:true">播放
                </el-button>
              </template>
              <el-button type="primary" :icon="Plus" @click="addPlayList"
                v-if="songs.fee != 1 && !songs.license &&  musicSuccess">添加到播放列表</el-button>
              <el-button type="primary" :icon="FolderAdd" v-if="songs.fee != 1 && !songs.license &&  musicSuccess"
                @click="openCollectionModal(Number(id))">收藏</el-button>
              <el-button :icon="Comment" @click="handleClickScrollToComment">评论 <span v-if="total>0">({{total}})</span>
              </el-button>
            </div>
            <!-- 歌词区域 -->
            <div class="jsp_container">
              <div class="jsp_pane">
                <div v-for="(item,index) in lrc" :key="item.time">
                  {{item.txt}}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="comment_wrapper" id="comment">
          <div class="top_b_m_tit" style="margin-top:50px">
            <div class="left_tit">
              <div>评论</div>
              <span>共{{total}}条评论</span>
            </div>
          </div>
          <div>
            <CommentComponent :commentType="2" :id="id" :isActiveId="false" :playlistLimit="20" :pageNum="pageNum"
              @getTotal="getTotal"></CommentComponent>
          </div>
          <div class="pageination_center" style="margin-top:40px">
            <el-pagination background layout="prev, pager, next" :total="total" v-show="total > 0"
              v-model:currentPage="pageNum" :page-size="20" @current-change="handleCurrentChange" />
          </div>
        </div>
      </el-col>
      <el-col :lg="4">
        <div class="right_other_container">
          <!-- 包含这首歌的歌单 -->
          <div class="have_music_list">
            <div class="ohter_title">
              包含这首歌的歌单
            </div>
            <div class="music_item" v-for="item in playlists" :key="item.id">
              <div class="left_img cursor_class">
                <img :src="item.coverImgUrl + '?param=50y50'" alt="" @click="handleClickToPlayListDetail(item.id)">
              </div>
              <div class="right_info">
                <div class="top_title cursor_class text_ellipsis text_decoration"
                  @click="handleClickToPlayListDetail(item.id)">{{item.name}}</div>
                <div class="bottom_by cursor_class text_ellipsis">
                  by <span class="text_decoration"
                    @click="()=>{router.push({name:'user-home',params:{id:item.creator.userId}})}">{{item.creator.nickname}}</span>
                </div>
              </div>
            </div>
          </div>
          <!-- 相似歌曲 -->
          <div class="like_music_list">
            <div class="ohter_title">
              相似歌曲
            </div>
            <div class="like_music_item" v-for="item in simiSongs" :key="item.id">
              <div class="left_music_info text_ellipsis">
                <div class="music_title text_ellipsis cursor_class text_decoration"
                  @click="handleClickSimiSongName(item.id)">{{item.name}}</div>
                <span class="music_singer text_ellipsis" v-for="(items,indexs) in item.artists">
                  <span v-if="indexs !== 0"> / </span>
                  <span class="text_ellipsis cursor_class text_decoration"
                    @click="()=>{router.push({name:'artist-detail',params:{id:items.id}})}">{{items.name}}</span>
                </span>
              </div>
              <div class="right_opeation">
                <el-tooltip effect="dark" content="播放" placement="top-start">
                  <span class="cursor_class" style="margin-right:20px" @click="simiPlay(item.id)">
                    <el-icon>
                      <VideoPlay />
                    </el-icon>
                  </span>
                </el-tooltip>
                <el-tooltip effect="dark" content="添加到播放列表" placement="top-start">
                  <span class="cursor_class" @click="simiAddPlayList(item.id)">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </span>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
  <Collection ref="collectionRef" />
  <!-- 登录注册弹窗 -->
  <LoginAndRegister ref="loginAndRegisterRef" />
</template>

<script lang="ts" setup>
import { isRef, reactive, ref, toRefs, watch } from "vue"
import { Headset, Plus, Timer, VideoPlay, Comment, FolderAdd, Pointer, PriceTag, House, Sunny, Guide, MostlyCloudy } from '@element-plus/icons-vue'
import CommentComponent from "@/components/Comment/index"
import router from '@/router';
import { useRoute } from "vue-router";
import { ElMessage } from 'element-plus'
import { getSongDetail, getSongLyric, getSimiSong, getSimiPlayList } from "@/api/song";
import Collection from "@/components/Collection/index"
import { collectionTypeRef } from "@/types/collection";
import Lyric from "lyric-parser"
import LoginAndRegister from '@/components/LoginAndRegister/index'
import { loginAndRegisterTypeRef } from "@/types/login";
import dayjs from "dayjs";
import { checkMusic } from "@/api/my-music";
const loginAndRegisterRef = ref<loginAndRegisterTypeRef | null>()
import { useStore } from "vuex";
const store = useStore();
const route = useRoute()
// 音乐是否可用
const musicSuccess = ref<boolean>(true)
// 路由参数
let id = route.params.id
const pageNum = ref(1)
const total = ref(0)
const collectionRef = ref<collectionTypeRef | null>(null)
const songDetailData = reactive<any>({
  privileges: {},
  songs: {
    ar: [{}],
    al: {}
  }
})
const songLrcData = reactive<any>({
  lrc: [{}]
})
const simiSongData = reactive<any>({
  simiSongs: [{ artists: {} }]
})
const simiPlayListData = reactive<any>({
  playlists: [{ creator: {} }]
})
const { privileges, songs } = toRefs(songDetailData)
const { lrc } = toRefs(songLrcData)
const { simiSongs } = toRefs(simiSongData)
const { playlists } = toRefs(simiPlayListData)
// 获取歌曲详情信息
const getSongDetailData = async () => {
  const res: any = await getSongDetail({
    ids: id
  })
  songDetailData.privileges = res.privileges
  // 只要第一个 歌曲详情页不可能渲染多个歌曲的
  songDetailData.songs = res.songs[0]
  checkMusicData(songDetailData.songs.id)
}
const checkMusicData = async (musicId: number) => {
  const res: any = await checkMusic({
    id: musicId
  })
  if (res.success) {
    musicSuccess.value = true
  } else {
    musicSuccess.value = false
  }
}
// 获取歌词
const getSongLyricData = async () => {
  const res: any = await getSongLyric({
    id
  })
  if (res.lrc.lyric) {
    // 歌词格式化
    // const lrcFormatRes = formatMusicLyrics(res.lrc.lyric)
    // console.log(lrcFormatRes);
    // songLrcData.lrc = lrcFormatRes.lyric
    // console.log(lrcFormatRes.lyric);
    let lyric = new Lyric(res.lrc.lyric)
    lyric.lines.forEach((item: any) => {
      item.time = dayjs(item.time).format("mm:ss")
    })
    // console.log(lyric.lines);
    songLrcData.lrc = lyric.lines
  }
}
// 获取相似歌手
const getSimiSongData = async () => {
  const res: any = await getSimiSong({ id })
  simiSongData.simiSongs = res.songs
}
// 获取相似歌单
const getSimiPlayListData = async () => {
  const res: any = await getSimiPlayList({ id })
  simiPlayListData.playlists = res.playlists
}
const handleCurrentChange = (val: number) => {
  pageNum.value = val
}
const getTotal = (val: number) => {
  total.value = val
}
// 点击评论跳转指定位置
const handleClickScrollToComment = () => {
  document.getElementById('comment')?.scrollIntoView()
}
// 点击相似歌曲名字
const handleClickSimiSongName = (id: number) => {
  router.push({
    name: 'song',
    params: {
      id
    }
  })
}
// 点击相似歌单
const handleClickToPlayListDetail = (id: number) => {
  router.push({
    name: 'play-list-detail',
    params: {
      id
    }
  })
}
// 打开收藏组件
const openCollectionModal = (id: number) => {
  let cookie = localStorage.getItem('cookie')
  if (cookie) {
    if (collectionRef.value) {
      collectionRef.value.id = id
      collectionRef.value.isSongSheet = false
      collectionRef.value.dialogVisible = true
      collectionRef.value.init()
    }
  } else {
    if (loginAndRegisterRef.value) {
      console.log(loginAndRegisterRef.value.loginVisible);
      loginAndRegisterRef.value.loginVisible = true
      loginAndRegisterRef.value.getQrKeyData()
    }
  }
}
watch(() => router.currentRoute.value.path, (newValue, oldValue) => {
  console.log('路由变化了哦');
  // location.reload()
  id = route.params.id
  if (id && router.currentRoute.value.name === 'song') {
    getSongDetailData()
    getSongLyricData()
    getSimiSongData()
    getSimiPlayListData()
  }
})
// 播放
const play = () => {
  store.dispatch('playAll', { list: [songs.value] });
}
// 添加到播放列表
const addPlayList = () => {
  store.dispatch('addList', { list: [songs.value] });
}
// 相似歌曲播放
const simiPlay = async (id: any) => {
  const res: any = await getSongDetail({
    ids: id
  })
  console.log(res.songs);
  store.dispatch('playAll', { list: [res.songs[0]] });
}
const simiAddPlayList = async (id: any) => {
  const res: any = await getSongDetail({
    ids: id
  })
  store.dispatch('addList', { list: [res.songs[0]] });
}
if (id) {
  getSongDetailData()
  getSongLyricData()
  getSimiSongData()
  getSimiPlayListData()
} else {
  ElMessage({
    message: "参数错误",
    type: 'error',
    duration: 2000,
    onClose: () => {
      history.go(-1)
    }
  })
}
</script>
<style lang="scss" scoped>
.song_contaner {
  margin-top: 20px;

  .song_warpper {
    display: flex;

    .left_song_img {
      width: 260px;
      height: 260px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .right_song_info {
      padding-left: 40px;
      flex: 1;

      .song_title {
        display: flex;
        align-items: center;
        margin-bottom: 20px;

        h1 {
          margin: 0;
          font-size: 24px;
          color: #333;
          margin-left: 14px;
        }
      }

      .song_desc {
        .song_desc_item {
          margin: 15px 0px;
          font-size: 12px;
          display: flex;
          align-items: center;

          span {
            margin-right: 4px;
            color: rgb(153, 153, 153);
          }
        }
      }

      .r_m_opea {
        margin-top: 20px;

        button {
          margin-bottom: 10px;
          margin-left: 0;
          margin-right: 10px;
        }
      }

      .jsp_container {
        height: 410px;
        overflow: auto;
        margin-top: 30px;

        .jsp_pane {
          font-size: 15px;
          color: #333;
          font-family: Arial, Helvetica, sans-serif;
          line-height: 2;
        }
      }
    }
  }

  .comment_wrapper {
    .top_b_m_tit {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 2px solid #409eff;
      padding-bottom: 10px;

      .left_tit {
        color: #333;
        font-size: 20px;
        display: flex;

        span {
          color: #666;
          font-size: 12px;
          margin-top: 10px;
          margin-left: 14px;
        }
      }
    }
  }

  .right_other_container {
    .have_music_list {
      .music_item {
        display: flex;
        margin: 14px 0;

        .left_img {
          width: 50px;
          height: 50px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .right_info {
          padding: 4px 0;
          padding-left: 10px;
          flex: 1;
          overflow: hidden;

          .top_title {
            font-size: 14px;
            margin-bottom: 10px;
          }

          .bottom_by {
            font-size: 12px;
            color: #999;

            span {
              color: #666;
            }
          }
        }
      }
    }

    .like_music_list {
      margin-top: 40px;

      .like_music_item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 16px 0;

        .left_music_info {
          font-size: 12px;
          overflow: hidden;
          flex: 1;

          .music_title {
            color: #333;
            margin-bottom: 8px;
          }

          .music_singer {
            color: #999;
            // margin-top: 8px;
            // display: inline-block;
          }
        }

        .right_opeation {
          padding-left: 10px;
        }
      }
    }

    .ohter_title {
      font-weight: 700;
      font-size: 12px;
      color: #333;
      border-bottom: 1px solid #ccc;
      padding-bottom: 10px;
    }
  }
}
</style>
